package com.ck.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ck.common.bean.McApiUserAuth;
import com.ck.common.utils.jwt.RedisCache;
import com.ck.system.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * @author ck
 * @date 2024/1/19 17:41
 */
@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    @Autowired
    RedisCache redisCache;

    private final static String REDIS_TOKEN = "Auth:";
    @Override
    public void setUserAuthMapInRedisCache(String keyToken, McApiUserAuth mcApiUserAuth , Long Id) {
        String cacheKey = REDIS_TOKEN + Id + ":keyToken:";
        Collection<String> keys = redisCache.keys(cacheKey + "*");
        if (CollectionUtils.isNotEmpty(keys)) {
            //删除缓存
            redisCache.deleteObject(keys);
        }
        redisCache.setCacheObject(cacheKey + keyToken, mcApiUserAuth, 1, TimeUnit.DAYS);
    }

    @Override
    public McApiUserAuth getUserAuthMapInRedisCache(String keyToken, Long id) {
        String cacheKey = REDIS_TOKEN + id + ":keyToken:";
        Object result = redisCache.getCacheObject(cacheKey + keyToken);
        if (result instanceof McApiUserAuth){
            return (McApiUserAuth) result;
        } else {
            return new McApiUserAuth();
        }

    }
}
